package com.example.service.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import com.example.service.R;

public class MyService extends Service { //继承Service类
    public MyService() {
    }

    private final String TAG = "MyService" ;
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        Log.d(TAG,"onCreate");

        //如果你在Android 8.0及以上版本上运行应用，确保你已经正确创建并配置了通知渠道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager manager = getSystemService(NotificationManager.class);
            NotificationChannel channel = new NotificationChannel("my_channel", "Channel human readable name",
                    NotificationManager.IMPORTANCE_DEFAULT);
            manager.createNotificationChannel(channel);
        }

        //1、创建通知
        Notification notification = new NotificationCompat.Builder(this,"my_channel")
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setContentTitle("这是通知标题")
                .setContentText("这是通知内容")
                .build();
        //2、升级为前台
        startForeground(1,notification);
        super.onCreate();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG,"onStartCommand");
        String value = intent.getStringExtra("key_stop");
        if("stop".equals(value)){
            stopSelf();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Log.d(TAG,"onDestroy");
        super.onDestroy();
    }

}